package com.example.websocket.server;

import io.micrometer.common.util.StringUtils;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * WebSocket服务端
 *
 * @author raos
 * @date 2024-03-04 17:37
 */
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {

    /*** 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的 */
    private static int onlineCount = 0;

    /*** concurrent包的线程安全集合，也可以map改成set，用来存放每个客户端对应的MyWebSocket对象 */
    private static final Map<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();

    /*** 与某个客户端的连接会话，需要通过它来给客户端发送数据 */
    private Session session;

    /*** 接收userId */
    private String userId = "";

    public static Map<String, WebSocketServer> getWebSocketMap() {
        return webSocketMap;
    }

    /*** 连接建立成功调用的方法 */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (!webSocketMap.containsKey(userId)) {
            // 加入集合中
            webSocketMap.put(userId, this);
            // 在线数加1
            addOnlineCount();
        }
        try {
            sendMessage("连接成功");
            log.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("用户:" + userId + ",网络异常!!!!!!");
        }
    }

    /*** 连接关闭调用的方法 */
    @OnClose
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            // 从集合中删除
            subOnlineCount();
        }
        log.info("用户退出:" + userId + ",当前在线人数为:" + getOnlineCount());
    }

    /***
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【websocket消息】收到客户端发来的消息:{}", message);
        try {
            // 模拟接收客户端消息后发送业务
            WebSocketServer.sendInfo(message, userId);
        } catch (IOException e) {
            log.error("收到客户端消息", e);
        }
    }

    /***
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /*** 实现服务器主动推送 */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /*** 发送自定义消息 */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException {
        log.info("发送消息到:" + userId + "，报文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        } else {
            log.error("用户" + userId + ",不在线！");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}
